package ua.kharkov.knure.pereverziev.diploma.web.command;

import java.io.IOException;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.ServiceFactory;
import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.UserService;
import ua.kharkov.knure.pereverziev.diploma.db.entity.User;

public class RegistrationCommand implements Command {

	private static final Logger log = Logger
			.getLogger(RegistrationCommand.class);

	@Override
	public String execute(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {
		log.debug("Command starts");

		log.info("Request encording " + request.getCharacterEncoding());
		request.setCharacterEncoding("UTF-8");

		final HttpSession session = request.getSession();

		final String password = request.getParameter("password");
		// TODO REMOVE FROM THE PRODUCTION
		// log.info("Request parameter: password --> " + password);

		final String confirmPassword = request.getParameter("confirmPassword");
		// TODO REMOVE FROM THE PRODUCTION
		// log.info("Request parameter: confirmPassword --> " +
		// confirmPassword);

		final String name = request.getParameter("name");
		log.info("Request parameter: name --> " + name);

		final String surname = request.getParameter("surname");
		log.info("Request parameter: surname --> " + surname);

		final String email = request.getParameter("email");
		log.info("Request parameter: email --> " + email);

		// error handler
		// set forward to error page

		String forward = "/WEB-INF/jsp/registration.jsp?error=Some error occured";
		final StringBuilder errorMessage = new StringBuilder();

		final UserService userService = new UserService();

		if (email.isEmpty()) {
			errorMessage.append("E-mail is empty ");
		} else {
			final Pattern p = Pattern
					.compile("^[_a-zA-z0-9-]+(.[_a-zA-z0-9-]+)*@[a-zA-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$");
			final Matcher m = p.matcher(email);
			if (!m.matches())
				errorMessage.append("Wrong email\n");
		}

		if (password.isEmpty()) {
			errorMessage.append("Password is empty\n");
		}
		if (confirmPassword.isEmpty()) {
			errorMessage.append("Password conformation is empty\n");
		}
		if (name.isEmpty()) {
			errorMessage.append("Name is empty\n");
		}
		if (surname.isEmpty()) {
			errorMessage.append("Surname is empty\n");
		}
		if (!password.equals(confirmPassword)) {
			errorMessage.append("Wrong password conformation\n");
		}

		// go to the error page if error message not empty
		if (errorMessage.length() == 0) {
			final User user = new User();
			user.setRegistrationDate(new java.sql.Date(Calendar.getInstance()
					.getTime().getTime()));
			user.setName(name);
			user.setSurname(surname);
			user.setPassword(password);
			user.setEmail(email);
			user.setStatus(ServiceFactory.getInstance().getUserStatusService()
					.getStatysByName("Customer"));
			user.setRole(ServiceFactory.getInstance().getUserRoleService()
					.getRoleByName("User"));
			if (userService.checkPresence(email)) {
				errorMessage
						.append("User with such email is already registered\n");
				log.error("User with such email is already registered");
			} else {
				userService.create(user);
				if (user.getId() == null) {
					errorMessage.append("Cannot insert data in database\n");
					log.error("Cannot insert data in database");
				} else {
					session.setAttribute("user", user);
					log.info("Set the session attribute: user --> " + user);
					forward = "controller?command=login&email="
							+ user.getEmail() + "&password="
							+ user.getPassword();
				}
			}
		}

		session.setAttribute("errorMessage", errorMessage);
		log.info("Set the session attribute: errorMessage --> " + errorMessage);

		if (!errorMessage.toString().isEmpty()) {
			forward = "/WEB-INF/jsp/registration.jsp?error="
					+ errorMessage.toString().replace("\n", "<br/>");
		} else {
			session.setAttribute("lastPage", forward);
		}
		log.debug("Command finished");
		return forward;
	}
}
